package edu.towson.cosc.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.towson.cosc.client.GreetingService;
import edu.towson.cosc.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	private static final Reader Srting = null;

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 10 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);	
		
		/*
		Pattern pattern = Pattern.compile("(\\b\\w+\\b).*?(\\b\\1\\b)");  // use pattern to split words
        int numberofline = 0;
        String linestr = null;
        String allstr = null;         
        String[] readline = null; 
        readline = input.split("\n");        // split line
        for (int i=0; i < readline.length; i++) { 
            numberofline++;
        	int j=0;
            Matcher matcher = pattern.matcher(readline[j]);   // compare the words        
            
            while (matcher.find()) {
                linestr = "the line:" + Intger.toString(line) + " " + matcher.group(1) ; 
                matcher.region(matcher.start() + 1, readline[j].length());              
            }
            j++;
            
        }
        allstr = allstr +linestr;
            
		return allstr;
		*/	
		
		
		/**
		 * Process the output 
		 */
		String allstr = " ";
		String lastWord = " ";
		int numberOfLines = 1;		
   		String[]line = input.split("\n");  	
   		for (int i=0; i < line.length; i++) { 			
   			 			
   			{	
   				line[i] = line[i].replaceAll ("[^a-zA-Z0-9 ]", "");   // Remove all non alpha-numeric characters
   				line[i] = line[i].toLowerCase();			// Splits the line into words and puts in an array of strings
   				String[] words = line[i].split (" ");    // Splits the line into words and puts in an array of strings
   				
   				for (int j=0; j<words.length-1; j++)    // Splits words from each line and puts in an array of strings
   				{	
   					if (words[0].equals (lastWord))		// Compare with the last word on the previous line
   						allstr = allstr + "Repeated word on line " + numberOfLines + ": " + words[0] + "<br>";  //Save the result to the output string
   					
   					if (words[j].equals (words [j+1]))	// Check to see if the current and subsequent words are the same
   	   					allstr = allstr + "Repeated word on line " + Integer.toString(numberOfLines) + ": " + words[j] + "<br>";   	//Save the result to the output string					
   				}
   				
   		   		numberOfLines++;	// Increment line counter
   		   		lastWord = words [words.length-1];  // Save last word in the line
   			}
   		}
   		
   		return allstr;
   			
	}
		
		
		
		
		

		
				//+ "!<br><br>I am running " + serverInfo
				//+ ".<br><br>It looks like you are using:<br>" + userAgent;
	

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
	
	
	
	 //use function to check stutter
	/* 
	public static String checkstutter (String input) throws IOException {
		
		Pattern pattern = Pattern.compile("(\\b\\w+\\b).*?(\\b\\1\\b)");  // use pattern to split words
        int line = 0;        
        String allstr = null;         
        String[] readline = null; 
        readline = input.split("\n");        
      for (int i=0;i<=readline.length;i++) {
           
           
            Matcher matcher = pattern.matcher(readline[i]);   // compare the words
       
            while (matcher.find()) {
                allstr = "the line:" +Integer.toString(line) + " " + matcher.group(1) + "\n"; // print output
                matcher.region(matcher.start() + 1, allstr.length());
            }
        }
		return allstr;
		
	}	*/

	
}
